package systempen.cmanager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import systempen.cmanager.DialogAccountBrowser.IFoundAccount;
import systempen.cmanager.DialogTypeBrowser.IFoundCostType;
import systempen.cmanager.R;
import systempen.cmanager.R.id;
import systempen.cmanager.R.layout;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

public class ReportDailyListParams extends AcitivityLowImportance {
	Activity thisclass;
	public TextView textFrom;
	public TextView textTo;
	public TextView textCost;
	public TextView textAccountName;
	public String _accountCode;
	String level;
	private static final int DATE_DIALOG_ID_from = 0;
	private static final int DATE_DIALOG_ID_to = 1;

	SQLiteDatabase db;
	Cursor c;
	String sqlDebug;
	String foundedType;
	private Context _context;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		try{
			super.onCreate(savedInstanceState);
			ThemePicker.onActivityCreateSetTheme(this);
			setContentView(R.layout.reportallbydateparams);
			thisclass = this;
			textFrom = (TextView) findViewById(R.id.txtFrom);
			textTo = (TextView) findViewById(R.id.txtTo);
			textCost = (TextView) findViewById(R.id.txtTypeName);
			textAccountName = (TextView) findViewById(R.id.txtAccountName);

			CheckBox cb = (CheckBox) findViewById(R.id.cbOnlyOneLevel);
			cb.setVisibility(View.GONE);
			level ="0";
			textFrom.setText(util.getDefaultFromDateView(getApplicationContext()));
			textTo.setText(util.getDefaultToDateView(getApplicationContext()));
			_context = getParent();
			if (_context ==null)
				_context = this;
		} catch(Exception ex){
			util.showDialog(ex.getMessage().toString(), thisclass);
		}
	}
	public void onRunReport (View view){
		try{
			String podtipovi = util.getAllChildren(level, thisclass);
			String sqlAccount;
			if ((_accountCode != null)&&(!_accountCode.equals(""))){
				sqlAccount = " and log.account = "+ _accountCode+" ";
			}
			else
			{
				sqlAccount = "";
			}

			sqlDebug = " select sum(value) as sum, log.whe"+
					" from log join cost_type on log.cost_code = cost_type.code "+
					" where log.whe >= '"+util.viewStringDateToDBStringDate(textFrom.getText().toString(), getApplicationContext()) +"'"+
					" and log.whe <= '"+util.viewStringDateToDBStringDate(textTo.getText().toString(), getApplicationContext()) +"'"+
					" and cost_type.code in("+podtipovi+")"+
					" and value > 0 "+
					sqlAccount+
					" group by log.whe"+
					" order by log.whe";
			util u = new util();
			c = u.getCursor(sqlDebug, thisclass);
			if (c.getCount()==0){
				Toast.makeText(getApplicationContext(), "No data effected.", Toast.LENGTH_SHORT).show();
				return;
			}
			startActivity(new ReportDailyListParams().execute(this,c));
		} catch(Exception ex){
			Toast.makeText(ReportDailyListParams.this, ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	////////////
	public Intent execute(Context context,Cursor c) {
		try{
			String[] titles = new String[] { "Costs by period" };
			int n = c.getCount();
			if (n==0){
				Toast.makeText(getApplicationContext(), "No data effected.", Toast.LENGTH_SHORT).show();
			}
			List<Date[]> dates = new ArrayList<Date[]>();
			List<double[]> values = new ArrayList<double[]>();
			double[] dabl = new double [n];
			Date[] dateValues = new Date[n];
			c.moveToFirst();
			int i = 0;
			String year;
			String month;
			String day;
			double max=0;
			if (c.getCount()>0){
				if (c.moveToFirst()) { 
					do {
						year = c.getString(1).substring(0, 4);
						month = c.getString(1).substring(5, 7);
						day = c.getString(1).substring(8, 10);
						dateValues[i] = new Date(Integer.parseInt(year)-1900, Integer.parseInt(month)-1, Integer.parseInt(day));
						dabl[i] = (c.getDouble(0));
						if (c.getDouble(0) >= max){
							max = c.getDouble(0);
						}

						i++;//mrzim ovo sranje
					} 
					while (c.moveToNext());} 
			}
			c.close();
			//db.close();
			values.add(dabl);
			dates.add(dateValues);
			int[] colors = new int[] { Color.RED };
			PointStyle[] styles = new PointStyle[] { PointStyle.POINT };
			XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
			setChartSettings(renderer, "Period costs", "Date", "SUM", dateValues[0].getTime(),
					dateValues[dateValues.length - 1].getTime(), 0, max, Color.GRAY, Color.LTGRAY);
			renderer.setYLabels(10);
			return ChartFactory.getTimeChartIntent(context, buildDateDataset(titles, dates, values), renderer, "MMM dd yyyy");
			//return ChartFactory.getPieChartIntent(context, categorySeries, renderer,"Daily distribution");
		}
		catch(Exception ex){
			Toast.makeText(ReportDailyListParams.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
			return null;
		}	
	}

	protected XYMultipleSeriesDataset buildDateDataset(String[] titles, List<Date[]> xValues,
			List<double[]> yValues) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		int length = titles.length;
		for (int i = 0; i < length; i++) {
			TimeSeries series = new TimeSeries(titles[i]);
			Date[] xV = xValues.get(i);
			double[] yV = yValues.get(i);
			int seriesLength = xV.length;
			for (int k = 0; k < seriesLength; k++) {
				series.add(xV[k], yV[k]);
			}
			dataset.addSeries(series);
		}
		return dataset;
	}


	protected void setChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle,
			String yTitle, double xMin, double xMax, double yMin, double yMax, int axesColor,int labelsColor) {
		renderer.setChartTitle(title);
		renderer.setXTitle(xTitle);
		renderer.setYTitle(yTitle);
		renderer.setXAxisMin(xMin);
		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);
		renderer.setAxesColor(axesColor);
		renderer.setLabelsColor(labelsColor);
	}


	protected XYMultipleSeriesRenderer buildRenderer(int[] colors, PointStyle[] styles) {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		renderer.setAxisTitleTextSize(16);
		renderer.setChartTitleTextSize(20);
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		renderer.setPointSize(5f);
		renderer.setMargins(new int[] { 20, 30, 15, 0 });
		int length = colors.length;
		for (int i = 0; i < length; i++) {
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setPointStyle(styles[i]);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

	protected DefaultRenderer buildCategoryRenderer(int[] colors) {
		DefaultRenderer renderer = new DefaultRenderer();
		for (int color : colors) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(color);

			renderer.addSeriesRenderer(r);
			renderer.setShowAxes(true);
			renderer.setLegendTextSize(26);
			renderer.setLabelsTextSize(22);
			renderer.setAntialiasing(true);
		}
		return renderer;
	}
	////////////

	public void onChangeFromDate (View view){
		try{
			showDialog(DATE_DIALOG_ID_from);
		} catch(Exception ex){
			util.showDialog(ex.getMessage().toString(), _context);
		}
	}
	public void onChangeToDate (View view){
		try{
			showDialog(DATE_DIALOG_ID_to);
		} catch(Exception ex){
			util.showDialog(ex.getMessage().toString(), _context);
		}
	}

	// Creating dialog
	@Override
	protected Dialog onCreateDialog(int id) {
		try{
			Calendar c = Calendar.getInstance();
			int cyear = c.get(Calendar.YEAR);
			int cmonth = c.get(Calendar.MONTH);
			int cday = c.get(Calendar.DAY_OF_MONTH);
			switch (id) {
			case DATE_DIALOG_ID_from:
				return new DatePickerDialog(_context,  mDateSetListener,  cyear, cmonth, cday);
			case DATE_DIALOG_ID_to:
				return new DatePickerDialog(_context,  mDateSetListener2,  cyear, cmonth, cday);
			}
		}
		catch(Exception ex){
			util.showDialog(ex.getMessage().toString(), _context);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		// onDateSet method
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			try{
				//String date_selected = String.valueOf(monthOfYear+1)+" /"+String.valueOf(dayOfMonth)+" /"+String.valueOf(year);
				String date_selected = String.valueOf(year)+"-"+util.AddZeros(monthOfYear+1)+"-"+util.AddZeros(dayOfMonth);

				Toast.makeText(ReportDailyListParams.this, "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
				textFrom.setText(util.dbStringDateToViewStringDate(date_selected, getApplicationContext()));
			}
			catch(Exception ex){
				util.showDialog(ex.getMessage().toString(), thisclass);
			}	
		}
	};
	private DatePickerDialog.OnDateSetListener mDateSetListener2 = new DatePickerDialog.OnDateSetListener() {
		// onDateSet method
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			try{
				String date_selected = String.valueOf(year)+"-"+util.AddZeros(monthOfYear+1)+"-"+util.AddZeros(dayOfMonth);
				Toast.makeText(ReportDailyListParams.this, "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
				textTo.setText(util.dbStringDateToViewStringDate(date_selected, getApplicationContext()));
			}
			catch(Exception ex){
				util.showDialog(ex.getMessage().toString(), thisclass);
			}	
		}
	};

	public void onChooseType (View view){
		IFoundCostType ifo = new IFoundCostType() {

			@Override
			public void onFoundCostType(String costType) {
				level = costType;
				foundedType = util.getLevelName(costType, getApplicationContext());
				textCost.setText(foundedType); 
			}
		};
		DialogTypeBrowser dt = new DialogTypeBrowser(_context, "0", ifo);
		dt.show();
	}
	public void onChooseAccount(View v){
		IFoundAccount ifa = new IFoundAccount() {

			@Override
			public void onFoundAccount(String account) {
				// TODO Auto-generated method stub
				_accountCode = account;
				textAccountName.setText(util.getAccountName(account, getApplicationContext()));
			}
		};
		DialogAccountBrowser dab = new DialogAccountBrowser(_context, ifa);
		dab.show();
	}

}

